<template>
    <div class="delete-bucket-page">
        <div class="page-header">
            <h2>删除 Bucket</h2>
            <p class="warning-text">
                当您不再需要保留某个存储空间（Bucket）时，可以将其删除。为免产生额外费用，请您及时删除。
            </p>
        </div>

        <!-- 状态1: 加载中 -->
        <div v-if="loadingCheck" class="checklist-loading">
            <el-skeleton :rows="5" animated />
        </div>

        <!-- 状态2: 加载完成，显示检查结果和操作按钮 -->
        <div v-else>
            <!-- 顶部警告栏 -->
            <el-alert :title="alertTitle" :type="alertType" :closable="false" show-icon class="top-alert" />

            <!-- “立即删除” 和 “刷新” 按钮 -->
            <div class="main-actions">
                <el-button type="danger" :loading="isDeleting" :disabled="isDeleteButtonDisabled"
                    @click="showFinalConfirmDialog">
                    立即删除
                </el-button>
                <el-button @click="runPreDeleteCheck">刷新</el-button>
            </div>

            <!-- 
        【核心修改】
        清空任务区域现在总是显示，只是内容根据数据动态变化
      -->
            <div class="task-section">
                <h4>清空任务</h4>
                <div class="task-list">
                    <h5>必删项 {{ requiredTasks.length }}</h5>
                    <div v-if="requiredTasks.length > 0" class="task-table">
                        <div class="task-table-header">
                            <span>资源</span>
                            <span>状态</span>
                            <span>操作</span>
                        </div>
                        <div v-for="reason in requiredTasks" :key="reason.id" class="task-table-row">
                            <span>{{ getTaskResourceName(reason.id) }}</span>
                            <span>{{ reason.description }}</span>
                            <span class="action-cell">
                                <el-button type="primary" link @click="handleTaskAction(reason.action_type)">
                                    {{ reason.action_text }}
                                </el-button>
                            </span>
                        </div>
                    </div>
                    <div v-else class="no-data">
                        <el-empty description="没有数据" :image-size="60" />
                    </div>
                </div>
                <!-- 未来可以添加“选删项”的逻辑 -->
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import apiClient from '@/api';
import { ElMessage, ElMessageBox, ElSkeleton, ElEmpty } from 'element-plus';

// props 和 router 保持不变
const props = defineProps({
    bucketName: { type: String, required: true },
});
const router = useRouter();

// ref 保持不变
const loadingCheck = ref(true);
const checkResult = ref(null);
const isDeleting = ref(false);


// 【新增】运行检查的函数，以便刷新按钮调用
const runPreDeleteCheck = async () => {
    loadingCheck.value = true;
    try {
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/pre-delete-check`);
        checkResult.value = response.data;
    } catch (error) {
        ElMessage.error(error.response?.data?.error || '预检查失败');
        checkResult.value = { can_delete: false, reasons: [] };
    } finally {
        loadingCheck.value = false;
    }
};

// onMounted 现在只调用这个函数
onMounted(runPreDeleteCheck);


// 【新增】计算属性，用于动态显示顶部 Alert 的标题
const alertTitle = computed(() => {
    if (!checkResult.value) return '正在检查...';
    if (checkResult.value.can_delete) {
        return '可以删除 Bucket，检测到您有 0 个选删项未清空。';
    }
    return `暂时无法删除，检测到您有 ${requiredTasks.value.length} 个必删项未清空。`;
});

// 【新增】计算属性，用于动态改变 Alert 类型
const alertType = computed(() => {
    if (!checkResult.value) return 'info';
    return checkResult.value.can_delete ? 'success' : 'warning';
});

// 【新增】计算属性，用于分离出必删项
const requiredTasks = computed(() => {
    // 假设所有返回的 reasons 都是必删项
    return checkResult.value?.reasons || [];
});

// isDeleteButtonDisabled 的逻辑保持不变
const isDeleteButtonDisabled = computed(() => {
    return loadingCheck.value || (checkResult.value && !checkResult.value.can_delete) || isDeleting.value;
});

// getTaskResourceName, handleTaskAction, showFinalConfirmDialog 函数都保持不变
const getTaskResourceName = (taskId) => ({
    clear_objects: '文件',
    clear_fragments: '分片 (碎片)',
}[taskId] || '未知资源');

// 【修改点 2】: 增加对 'link_to_fragments' 的处理
const handleTaskAction = (actionType) => {
    // 如果是清空文件 或 清理碎片，都跳转到文件列表页
    if (actionType === 'link_to_files' || actionType === 'link_to_fragments') {
        // (可选) 可以给一个更明确的提示
        if (actionType === 'link_to_fragments') {
            ElMessage.info('正在跳转... 请在文件列表页的“更多操作”中找到“碎片管理”。');
        }
        router.push({ name: 'BucketContents', params: { bucketName: props.bucketName } });
    }
};

const showFinalConfirmDialog = () => {
    ElMessageBox.confirm(
        `
      <div class="final-confirm-dialog">
        <div class="el-message-box__title" style="font-size: 16px; font-weight: 500;"><span>确认删除 Bucket？</span></div>
        <div class="el-alert el-alert--warning is-light" style="margin: 15px 0;">
          <div class="el-alert__content">
            <p class="el-alert__description">
              删除Bucket后，Bucket中的数据无法恢复，请在删除前确认数据已不再使用。请注意，删除Bucket后，需要等待数小时才能再次创建同名的Bucket。
            </p>
          </div>
        </div>
        <p>确认删除该 Bucket，请输入该 Bucket 的名称 <strong>${props.bucketName}</strong></p>
      </div>
    `,
        '确定删除吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showInput: true,
            inputPlaceholder: '请输入完整的存储桶名称',
            dangerouslyUseHTMLString: true,
            inputValidator: (value) => {
                if (value === props.bucketName) return true;
                return '输入的名称与目标存储桶不匹配';
            },
        }
    ).then(async () => {
        isDeleting.value = true;
        try {
            await apiClient.delete(`/api/v1/buckets/${props.bucketName}`);
            ElMessage.success(`存储桶 '${props.bucketName}' 已成功删除！`);
            router.push({ name: 'BucketList' });
        } catch (error) {
            ElMessage.error(error.response?.data?.error || '删除失败');
        } finally {
            isDeleting.value = false;
        }
    }).catch(() => {
        ElMessage.info('已取消删除操作');
    });
};
</script>

<style scoped>
/* 样式部分您的代码是完全正确的，无需修改 */
.page-header h2 {
    margin-bottom: 8px;
    font-size: 20px;
}

.warning-text {
    color: #606266;
    font-size: 14px;
}

.checklist-loading {
    margin-top: 20px;
}

.checklist-container {
    margin-bottom: 30px;
}

/* 增加一点下边距，和按钮分开 */
.task-list {
    margin-top: 20px;
    padding: 16px;
    background: #fafafa;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.task-item {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
}

.task-item:last-child {
    border-bottom: none;
}

.task-desc,
.task-status,
.task-action {
    font-size: 14px;
}

.task-desc span,
.task-status span {
    margin-left: 8px;
    color: #606266;
}

.task-action {
    text-align: right;
}

.delete-action-container {
    margin-top: 20px;
}

/* 添加或替换以下样式 */
.delete-bucket-page {
    padding: 24px;
    max-width: 900px;
}

.top-alert {
    margin-bottom: 20px;
}

.main-actions {
    margin-bottom: 30px;
}

.task-section {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.task-list h4,
.task-list h5 {
    margin: 0 0 15px 0;
    font-weight: 500;
}

.task-list h5 {
    color: #606266;
}

.task-table-header,
.task-table-row {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    align-items: center;
    padding: 12px 8px;
    font-size: 14px;
}

.task-table-header {
    background-color: #fafafa;
    color: #303133;
    font-weight: 500;
}

.task-table-row {
    border-bottom: 1px solid #f0f0f0;
}

.task-table-row:last-child {
    border-bottom: none;
}

.action-cell {
    text-align: right;
}

.no-data {
    padding: 20px 0;
}
</style>